package cn.dgfy.ssm.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

public class IPHelper {
	
	public static String getIPStringFromLongFormat(Long ip) {
		if (ip == null) {
			return null;
		}
		
		if (ip < 0 || ip > 4294967295L) {
			return null;
		}
		
		StringBuilder result = new StringBuilder(15);
		
		for (int i = 0; i < 4; i++) {
			result.insert(0, Long.toString(ip & 0xff));
			
			if (i < 3) {
				result.insert(0, '.');
			}
			
			ip = ip >> 8;
		}
		
		return result.toString();
	}
	
	public static Long getLongFormatFromIPString(String ip) {
		String[] ipArray = ip.split("\\.");
		
		if (ipArray.length != 4) {
			return null;
		}
		
		Long result = 0L;
		
		for (int i = 3; i >= 0; i--) {
			long ipLong = Long.valueOf(ipArray[3 - i]);
			
			if (ipLong < 0 || ipLong > 255) {
				return null;
			}
			
			result |= ipLong << (i * 8);
		}
		
		return result;
	}
	
	public static String getWebClientRealIP(HttpServletRequest request) {
		if (request == null) {
			return "0.0.0.0";
		}
		
		String ip = request.getHeader("X-Forwarded-For");
		
		if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
			if (ip.indexOf(",") != 1) {
				ip = ip.split(",")[0];
			}
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_Client_IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("X-Real-IP");
		}
		
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		
		if (ip == null || ip.equals("0:0:0:0:0:0:0:1") || ip.equals("127.0.0.1")) {
			ip = getLocalAddress();
		}
		
		return ip;
	}
	
	public static String getLocalAddress() {
		
		InetAddress inet;
		
		try {
			inet = InetAddress.getLocalHost();
		} catch (UnknownHostException e) {
			return "";
		}
		
		if (inet != null) {
			return inet.getHostAddress();
		} else {
			return "";
		}
	}
}
